package jfilters.filters.color;

/*
    Copyright Janne Liljeblad 2008.

    This file is part of JFilters.

    JFilters is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    JFilters is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with JFilters.  If not, see <http://www.gnu.org/licenses/>.
*/

import jfilters.filters.SingleInputFilter;
import jfilters.libcolor.JFColorSpace;
import java.awt.image.*;
import java.awt.*;

//--- gimp file: /plug-ins/common/colorify.c
public class JFColorify extends SingleInputFilter
{
	private Color col = new Color( 255, 255, 255, 255 );

	private int[] lum_red_lookup = new int[256];
	private int[] lum_green_lookup = new int[256];
	private int[] lum_blue_lookup = new int[256];
	private int[] final_red_lookup = new int[256];
	private int[] final_green_lookup = new int[256];
	private int[] final_blue_lookup = new int[256];

	public JFColorify(){}

	public void setColor( Color c )
	{ 
		col = c;

		for (int i = 0; i < 256; i ++)
		{
			lum_red_lookup[i]     = (int) ((float) i * JFColorSpace.JF_RGB_INTENSITY_RED );
			lum_green_lookup[i]   = (int) ((float) i * JFColorSpace.JF_RGB_INTENSITY_GREEN );
			lum_blue_lookup[i]    = (int) ((float) i * JFColorSpace.JF_RGB_INTENSITY_BLUE );

			final_red_lookup[i]   = (i * col.getRed() ) / 255;
			final_green_lookup[i] = (i * col.getGreen() ) / 255;
			final_blue_lookup[i]  = (i * col.getBlue() ) / 255;
		}
	}

	public BufferedImage filter( BufferedImage destinationImg )
	{
		WritableRaster destination = destinationImg.getRaster();

		int width  = destinationImg.getWidth();
		int height = destinationImg.getHeight();

		int[] dPixel = new int[ 4 ];
		int[] sPixel = new int[ 4 ];

		int lum;

		//--- Filter pixels
		for ( int y = 0; y < height; y++)
		{
			for (int x = 0; x < width; x++)
			{
				destination.getPixel( x, y, sPixel );
				lum = lum_red_lookup[ sPixel[RED] ]   +
					lum_green_lookup[ sPixel[GREEN] ] +
					lum_blue_lookup[ sPixel[BLUE] ];
			
			 	dPixel[RED] = final_red_lookup[lum];
				dPixel[GREEN] = final_green_lookup[lum];
			 	dPixel[BLUE] = final_blue_lookup[lum];
				dPixel[ALPHA] = sPixel[ALPHA];

				destination.setPixel( x, y, dPixel );
			}
		}
		
		return destinationImg;
	}

}//end class